import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
// console.log(localStorage.getItem('token') || '')
export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    // 1. 用来存储登录成功之后，得到的 token
    token: '',
    userInfo: {}
  },
  mutations: {
    // 2. 更新 token 的 mutation 函数
    updateToken (state, newToken) {
      state.token = newToken
    },
    updateUserInfo (state, obj) {
      state.userInfo = obj
    }
  },
  actions: {
    async initUserInfo (ctx) {
      const { data: res } = await axios.get('/my/userinfo', {
        headers: {
          Authorization: ctx.state.token
        }
      })
      if (res.code === 0) {
        ctx.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {
  }
})
